﻿using System;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using MvcMovie.Models;

namespace MvcMovie.Controllers
{
    public class MoviesController : Controller
    {
        private MovieDBContext db = new MovieDBContext();

        //
        // GET: /Movies/

        public ActionResult Index()
        {
            return View(db.Movies.ToList());
        }

        //
        // GET: /Movies/Details/5

        public ActionResult Details(Guid id)
        {
            Movie movie = db.Movies.Find(id);
            if (movie == null) return HttpNotFound();

            return View(movie);
        }

        //
        // GET: /Movies/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Movies/Create

        [HttpPost]
        public ActionResult Create(Movie movie)
        {
            if (ModelState.IsValid)
            {
                movie.ID = Guid.NewGuid();
                db.Movies.Add(movie);
                db.SaveChanges();

                return RedirectToAction("Index");
            }

            return View(movie);
        }

        //
        // GET: /Movies/Edit/5

        [HttpGet] // [06] Default attribute is HttpGet, can be ignored
        public ActionResult Edit(Guid id)
        {
            Movie movie = db.Movies.Find(id);
            if (movie == null) return HttpNotFound();

            return View(movie);
        }

        //
        // POST: /Movies/Edit/5

        [HttpPost] // [06] This overload of the Edit method can be invoked only for POST requests
        public ActionResult Edit(Movie movie)
        {
            if (ModelState.IsValid)
            {
                db.Entry(movie).State = EntityState.Modified;
                db.SaveChanges();

                return RedirectToAction("Index");
            }

            return View(movie);
        }

        //
        // GET: /Movies/Delete/5

        public ActionResult Delete(Guid id)
        {
            Movie movie = db.Movies.Find(id);
            if (movie == null) return HttpNotFound();

            return View(movie);
        }

        //
        // POST: /Movies/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(Guid id)
        {
            Movie movie = db.Movies.Find(id);

            db.Movies.Remove(movie);
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}